package com.xxc.response.handler;


import com.xxc.response.constant.Const;
import com.xxc.response.result.PlatformResult;
import com.xxc.response.utils.RequestContextHolderUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        Class type = (Class) RequestContextHolderUtil.getRequest().getAttribute(Const.RESPONSE_RESULT);
        return type != null;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Class type = (Class) RequestContextHolderUtil.getRequest().getAttribute(Const.RESPONSE_RESULT);
        if(body instanceof PlatformResult) {
            return body;
        }
        //如果是通用响应类则进行创建返回
        if(type == PlatformResult.class) {
            return new PlatformResult<>(200,"ok",body);
        }else{
            return body;
        }
    }
}